using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using WebServiceTool.Models;
using WebServiceTool.Utilities;

namespace WebServiceTool.Services
{
    /// <summary>
    /// WebService服务实现
    /// </summary>
    public class WebService : IWebService
    {

        #region 字段

        private readonly HttpClient _httpClient;
        private readonly WsdlParsingHelper _wsdlParsingHelper;
        private string _content;

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="wsdlParsingHelper">WSDL解析助手</param>
        public WebService(HttpClient httpClient, WsdlParsingHelper wsdlParsingHelper)
        {
            _httpClient = httpClient;
            _wsdlParsingHelper = wsdlParsingHelper;
        }

        #endregion

        #region IWebService实现

        /// <summary>
        /// 获取WSDL内容
        /// </summary>
        /// <param name="url">WSDL地址</param>
        /// <returns>WSDL内容</returns>
        public async Task<string> GetWsdlAsync(string url)
        {
            // 确保URL以.wsdl结尾或者添加?wsdl参数
            var wsdlUrl = url;
            if (!url.ToLower().EndsWith(".wsdl") && !url.ToLower().Contains("?wsdl"))
            {
                wsdlUrl = url + "?wsdl";
            }

            var response = await _httpClient.GetAsync(wsdlUrl);
            _content = await response.Content.ReadAsStringAsync();
            return _content;

        }

        /// <summary>
        /// 解析WSDL内容并提取服务方法
        /// </summary>
        /// <param name="wsdlContent">WSDL内容</param>
        /// <returns>服务方法列表</returns>
        public async Task<List<WebServiceOperation>> ParseWsdlMethods(string wsdlContent)
        {
            return await Task.Run(() =>
            {
                var methods = new List<WebServiceOperation>();
                try
                {
                    // 简单解析WSDL内容，提取方法名称
                    var doc = new XmlDocument();
                    doc.LoadXml(wsdlContent);

                    // 手动创建WsdlParsingHelper实例
                    _wsdlParsingHelper.GetMethods(doc, methods);
                }
                catch (Exception)
                {
                    // ignored
                }

                // 使用LINQ OrderBy方法排序，避免直接调用Sort方法需要实现IComparable接口的问题
                return methods.OrderBy(m => m.Name).ToList();
            });
        }

        /// <summary>
        /// 调用WebService方法
        /// </summary>
        ///  <param name="wsdlContent">wsdl内容</param>
        /// <param name="methodName">方法名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>调用结果</returns>
        public async Task<string> InvokeMethodAsync(string wsdlContent, string methodName, List<InputParameter> parameters)
        {
            // 简单解析WSDL内容，提取方法名称
            var doc = new XmlDocument();
            // 移除BOM解决XML解析错误
            doc.LoadXml(wsdlContent.TrimStart('\uFEFF'));
            // 清除默认请求头
            _httpClient.DefaultRequestHeaders.Clear();
            var targetNamespace = _wsdlParsingHelper.GetTargetNamespace(doc);
            // 构建SOAP请求
            var soapEnvelope = _wsdlParsingHelper.BuildSoapEnvelope(doc, targetNamespace, methodName, parameters);

            // 设置请求内容
            var content = new StringContent(soapEnvelope, Encoding.UTF8, "text/xml");

            // 获取请求地址
            var requestUrl = _wsdlParsingHelper.GetEndpointUrl(doc);
            

            // 添加SOAPAction URL
            var methodUrl = _wsdlParsingHelper.GetMethodUrl(doc, methodName);
            
            if (string.IsNullOrEmpty(methodUrl))
            {
                return "SOAPAction获取失败";
                
            }
            
          
            // headers.Add("SOAPAction", methodUrl);
            _httpClient.DefaultRequestHeaders.Add("Context-type", "text/xml");
            _httpClient.DefaultRequestHeaders.Add("SOAPAction", methodUrl);

            var response = await _httpClient.PostAsync(requestUrl, content);
            var responseContent = await response.Content.ReadAsStringAsync();

            // 检查响应状态码
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException(responseContent);
            }

            return _wsdlParsingHelper.ParseSoapResponse(responseContent);

        }

        #endregion

    }
}